<template>
  <div class="comment-post">
    <van-field
      type="textarea"
      rows="2"
      v-model="msg"
      autofocus
      maxlength="50"
      show-word-limit
    />
    <van-button type="primary" @click="onPost" :disabled="!msg"
      >发布</van-button
    >
  </div>
</template>

<script>
import { addComment } from '@/api/comment'
export default {
  props: {
    target: {
      type: [Number, String, Object],
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      default() {
        return null
      }
    }
  },
  data() {
    return {
      msg: ''
    }
  },
  methods: {
    async onPost() {
      this.$toast.loading({
        message: '发布中',
        forbidClick: true
      })
      const { data } = await addComment({
        // 评论的目标id
        // 用 toString 是为了当 id 是大 int 数据对象时，转换
        target: this.target.toString(),
        // 评论内容
        content: this.msg,
        // 文章id，评论文章时不用传递
        art_id: this.articleId ? this.articleId.toString() : null
      })
      console.log(data)
      this.$emit('post-success', data.data.new_obj)
      this.msg = ''
      this.$toast.success('发布成功')
    }
  }
}
</script>

<style lang="less" scoped>
.comment-post {
  display: flex;
  align-items: center;
}
</style>
